package com.jy.faceValidate.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FaceValidateUtils {

    static Logger logger = LoggerFactory.getLogger(FaceValidateUtils.class);

    public static FaceValidateBase faceV = FaceValidateBase.getInstance();

//    public static int tmpNum = 0;//专门记录出现比对失败返回负值的张数，如果大于 5 张，则重新初始化一次；

    static{
        synchronized(FaceValidateUtils.class){
            logger.info("初始化人脸识别模块.....");
            long startTimes = System.currentTimeMillis();
            System.loadLibrary("faceValidateDll");
            boolean flag = false;
            while(!flag){
                faceV.initBRL();
                flag = true;
            }
            long endTimes = System.currentTimeMillis();
            logger.info("初始化人脸识别模块完毕，耗时:"+ (endTimes - startTimes) +"毫秒");
        }
    }

    /**
     * 重新初始化人脸识别模块
     */
    public static void  reInitFaceValidate(){
        synchronized(FaceValidateUtils.class){
            logger.info("重新初始化人脸识别模块.....");
            long startTimes = System.currentTimeMillis();
            System.loadLibrary("faceValidateDll");
            boolean flag = false;
            while(!flag){
                faceV.initBRL();
                flag = true;
            }
            long endTimes = System.currentTimeMillis();
            logger.info("重新初始化人脸识别模块完毕，耗时:"+ (endTimes - startTimes) +"毫秒");
        }
    }

    /**
     * 比对两张图片的相似度
     * @param path1
     * @param path2
     * @return
     */
    public static float validateImg(String path1,String path2){

        float result = 0.0f;

        synchronized(FaceValidateUtils.class){

            long startTimes = System.currentTimeMillis();
            logger.info("开始比对照片【"+path1+"】和照片【"+path2+"】");


            try {

                result = FaceValidateUtils.faceV.validateImg(path1,path2);

            } catch (Exception e) {
                logger.error("开始比对照片【"+path1+"】和照片【"+path2+"】异常："+e.getMessage());
            }

            long endTimes = System.currentTimeMillis();

            logger.info("识别相似度:"+result);


            if(result < 0f || result > 1f){
//				if(++tmpNum > 50){
//					FaceValidateUtils.reInitFaceValidate();//重新初始化人脸识别模块
//					tmpNum = 0;
//				}

                result = 0.0f;
            }

            logger.info("耗时:"+ (endTimes - startTimes) +"毫秒");
        }


        return result;

    }

}
